package com.szpxt.action;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;
import com.szpxt.model.Privilege;
import com.szpxt.model.User;
import com.szpxt.service.UserService;

@Component @Scope("prototype")
public class LoginAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<String, Object> sessionMap;
	
	private UserService userService;
	
	public void login() throws NoSuchAlgorithmException, IOException {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		JSONObject jo = new JSONObject();
		User user = userService.login(name, password);
		if(user != null) {
			String strPrivilege = "";
			for(Privilege privilege: user.getRole().getListPrivilege()) {
				strPrivilege += privilege.getKey() + "-";
			}
			
			sessionMap.put("user", user);
			sessionMap.put("strPrivilege", strPrivilege);
			
			jo.put(SUCCESS, true);
		}
		else {
			jo.put(SUCCESS, false);
		}
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	//获取和设置方法
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}
